import { _decorator } from "cc";
import Singleton from "../base/Singleton";
const { ccclass } = _decorator;

@ccclass("EventManager")
export class EventManager extends Singleton {
  static get Instance(): EventManager {
    return super.getInstance<EventManager>();
  }

  private _eventMap: Map<string, Array<Function>> = new Map();

  on(eventType: string, callback: Function) {
    if (this._eventMap.has(eventType)) {
      this._eventMap.get(eventType).push(callback);
    } else {
      this._eventMap.set(eventType, [callback]);
    }
  }

  off(eventType: string, callback: Function) {
    const callbacks = this._eventMap.get(eventType);
    if (callbacks) {
      this._eventMap.set(
        eventType,
        callbacks.filter((cb) => cb !== callback)
      );
    }
  }

  clear() {
    this._eventMap.clear();
  }

  emit(eventType: string, ...args: any[]) {
    const callbacks = this._eventMap.get(eventType);
    if (callbacks) {
      callbacks.forEach((cb) => cb(...args));
    }
  }
}
